package team.yidong.fenda.serviceImpl;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import team.yidong.fenda.entity.Hospital;
import team.yidong.fenda.entity.Question;
import team.yidong.fenda.entity.User;
import team.yidong.fenda.repository.HospitalRepository;
import team.yidong.fenda.repository.QuestionRepository;
import team.yidong.fenda.repository.UserRepository;
import team.yidong.fenda.service.HospitalService;
import team.yidong.fenda.service.UserService;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by xuanlong on 2017/10/23.
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserRepository userRepository;
    @Autowired
    HospitalRepository hospitalRepository;
    @Autowired
    QuestionRepository questionRepository;

    @Override
    public JSONObject findUser(Integer hospitalId, String hospitalName, Integer limit, Integer offset, String wxNumber, String name, Double score) {
        Pageable pageable = new PageRequest(offset, limit, Sort.Direction.ASC, "id");
        Page<User> userPage = userRepository.findAll(new Specification<User>() {
            List<Predicate> predicateList = new ArrayList<>();

            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                if (hospitalId != 1) {
                    Hospital hospital = hospitalRepository.findOne(hospitalId);
                    Predicate p1 = criteriaBuilder.equal(root.get("hospital").as(Hospital.class), hospital);
                    predicateList.add(p1);

                } else if (hospitalName != null && !hospitalName.equals("")) {

                    Hospital hospital = hospitalRepository.findByNameLike("%" + hospitalName + "%");
                    Predicate p = criteriaBuilder.equal(root.get("hospital").as(Hospital.class), hospital);
                    predicateList.add(p);

                }
                if (wxNumber != null && !wxNumber.equals("")) {
                    Predicate p = criteriaBuilder.like(root.get("wxNumber").as(String.class), "%" + wxNumber + "%");
                    predicateList.add(p);
                }
                if (name != null && !name.equals("")) {
                    Predicate p = criteriaBuilder.like(root.get("name").as(String.class), "%" + name + "%");
                    predicateList.add(p);
                }
                if (score != null && !score.equals("")) {
                    Predicate p = criteriaBuilder.equal(root.get("score").as(Double.class), score);
                    predicateList.add(p);
                }
                criteriaQuery.where(predicateList.toArray(new Predicate[predicateList.size()]));

                return null;
            }
        }, pageable);
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.setExcludes(new String[]{"hospitalPermissionSet", "hospitalImgSet", "hospitalFieldList", "userSet", "masterList"});
        JSONObject jsonObject = JSONObject.fromObject(userPage, jsonConfig);
        String temp = "{\"total\":" + jsonObject.getString("totalElements") + ",\"rows\":" + jsonObject.getString("content") + "}";
        JSONObject j = JSONObject.fromObject(temp);
        return j;
    }

    @Override
    public User findByUserId(Integer userId) {
        return userRepository.findOne(userId);
    }

    @Transactional
    @Override
    public void addUser(String wxNumber, String name, String info, String hospitalName) {
        try {
            User user = new User();
            user.setUserOpenId(wxNumber);
            user.setName(name);
            user.setInfo(info);
            user.setScore(0.0);
            Hospital hospital = hospitalRepository.findByName(hospitalName);
            user.setHospital(hospital);
            userRepository.save(user);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Transactional
    @Override
    public void deleteUser(Iterable<User> userIterable) {
        userRepository.delete(userIterable);
    }

    @Transactional
    @Override
    public void updateUser(User user) {
        userRepository.save(user);
    }

    @Transactional
    @Override
    public void changeUserBlack(Integer userId, Integer questionId) {
        User user = userRepository.findOne(userId);
        user.setIsBlack("是");
        Question question = questionRepository.findOne(questionId);
        question.setStatus("black");
        questionRepository.save(question);
    }

}
